"""基础检测平台抽象类"""

import uuid
from abc import ABC, abstractmethod
from typing import Optional, Dict, Any
from datetime import datetime

from app.models.enums import DetectionStatus, DetectionPlatform
from app.models.response import TextDetectionResponse
from app.utils.logger import get_logger

logger = get_logger("platform.base")


class BaseDetectionPlatform(ABC):
    """基础检测平台抽象类"""
    
    def __init__(self, api_url: str, api_key: str, platform_name: DetectionPlatform):
        self.api_url = api_url
        self.api_key = api_key
        self.platform_name = platform_name
        self.logger = get_logger(f"platform.{platform_name.value}")
    
    @abstractmethod
    async def submit_detection(self, text: str, title: Optional[str] = None, 
                             author: Optional[str] = None) -> TextDetectionResponse:
        """提交检测任务"""
        pass
    
    @abstractmethod
    async def get_detection_result(self, task_id: str) -> TextDetectionResponse:
        """获取检测结果"""
        pass
    
    @abstractmethod
    async def cancel_detection(self, task_id: str) -> bool:
        """取消检测任务"""
        pass
    
    def generate_task_id(self) -> str:
        """生成任务ID"""
        return str(uuid.uuid4())
    
    def validate_api_connection(self) -> bool:
        """验证API连接"""
        try:
            # 这里应该实现实际的API连接测试
            self.logger.info(f"验证 {self.platform_name.value} API连接")
            return True
        except Exception as e:
            self.logger.error(f"API连接验证失败: {e}")
            return False
    
    def _create_response(self, task_id: str, status: DetectionStatus, 
                        similarity_rate: Optional[float] = None,
                        report_url: Optional[str] = None) -> TextDetectionResponse:
        """创建标准响应"""
        return TextDetectionResponse(
            task_id=task_id,
            status=status,
            platform=self.platform_name,
            similarity_rate=similarity_rate,
            report_url=report_url,
            created_at=datetime.now()
        )
    
    async def _make_api_request(self, method: str, endpoint: str, 
                               data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """发起API请求的通用方法"""
        try:
            # 这里应该实现真实的HTTP请求逻辑
            self.logger.info(f"发送 {method} 请求到 {endpoint}")
            
            # 模拟API响应
            mock_response = {
                "success": True,
                "task_id": self.generate_task_id(),
                "status": "pending",
                "message": "任务已提交"
            }
            
            return mock_response
            
        except Exception as e:
            self.logger.error(f"API请求失败: {e}")
            raise
    
    def _prepare_headers(self) -> Dict[str, str]:
        """准备请求头"""
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "User-Agent": "TextDetectionAPI/1.0.0"
        }
    
    def _validate_text_for_platform(self, text: str) -> bool:
        """验证文本是否适合该平台检测"""
        # 基础验证，子类可以重写
        if not text or len(text.strip()) == 0:
            return False
        
        # 检查平台特定的文本要求
        return self._platform_specific_validation(text)
    
    @abstractmethod
    def _platform_specific_validation(self, text: str) -> bool:
        """平台特定的文本验证（子类实现）"""
        pass
    
    def get_platform_info(self) -> Dict[str, Any]:
        """获取平台信息"""
        return {
            "name": self.platform_name.value,
            "api_url": self.api_url,
            "is_available": self.validate_api_connection(),
            "features": self._get_platform_features()
        }
    
    @abstractmethod
    def _get_platform_features(self) -> list[str]:
        """获取平台特性列表（子类实现）"""
        pass 